import gnomekeyring

class Keyring(object):
    def __init__(self, name, protocol):
        self.name = name
        self.protocol = protocol
        self.keyring = gnomekeyring.get_default_keyring_sync()

    def get_credentials_list(self, server):
         try:
            attrs = {
                "server": server,
                "protocol": self.protocol
            }
            items = gnomekeyring.find_items_sync(gnomekeyring.ITEM_NETWORK_PASSWORD, attrs)
            return items
         except gnomekeyring.NoMatchError:
             return None       

    def get_credentials(self, server, user):
        try:
            attrs = {
                "server": server,
                "protocol": self.protocol
            }
            items = gnomekeyring.find_items_sync(gnomekeyring.ITEM_NETWORK_PASSWORD, attrs)
            for item in items:
                if item.attributes["user"] == user:
                    return item
            return None
        except gnomekeyring.NoMatchError:
            return None

    def get_credentials_by_id(self, server, id):
        try:
            attrs = {
                "server": server,
                "protocol": self.protocol
            }
            items = gnomekeyring.find_items_sync(gnomekeyring.ITEM_NETWORK_PASSWORD, attrs)
            for item in items:
                print "matching " + str(item.item_id) + " with " + str(id)
                if item.item_id == id:
                    return item
            return None
        except gnomekeyring.NoMatchError:
            return None
        
    def has_credentials(self, server):
        try:
            attrs = {
                    "server": server,
                    "protocol": self.protocol
            }
            items = gnomekeyring.find_items_sync(gnomekeyring.ITEM_NETWORK_PASSWORD, attrs)
            return len(items) > 0

        except gnomekeyring.NoMatchError:
            return False

    def set_credentials(self, (user, password), server):
        attrs = {
            "user": user,
            "server": server,
            "protocol": self.protocol
        }

        gnomekeyring.item_create_sync(
            self.keyring,
            gnomekeyring.ITEM_NETWORK_PASSWORD,
            self.name,
            attrs,
            password,
            True
        )

    def forget_credentials(self, user, server):
        try:
            attrs = {
                "user": user,
                "server": server,
                "protocol": self.protocol
            }
            items = gnomekeyring.find_items_sync(gnomekeyring.ITEM_NETWORK_PASSWORD, attrs)
            return len(items) > 0
        except gnomekeyring.NoMatchError:
            return False

        for item in items:
            if item.attributes["user"] == user:
                print "Deleting: " + item.attributes["user"]
                gnomekeyring.item_delete_sync(self.keyring, 4)

